﻿using System.IO;
using System.Text;

namespace WebAPI.Utils
{
    public class FileUtil
    {
        // 读取文件
        public static string Read(string filePath)
        {
            using FileStream fs = new(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            using StreamReader sr = new(fs, Encoding.UTF8);
            var json = sr.ReadToEnd();
            return json;
        }

        // 写入文件
        public static void Write(string filePath, string content)
        {
            using FileStream fs = new(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            using StreamWriter sw = new(fs, Encoding.UTF8);
            sw.WriteLine(content);
        }

        public static void Write(string filePath, string content, bool append)
        {
            using var writer = new StreamWriter(filePath, append);
            writer.Write(content); // 或者使用 writer.WriteLine(content); 来在内容后添加一个换行符
        }
        
        // 写入
        //File.WriteAllText(filePath, content);
        
        // 追加
        //File.AppendAllText(filePath, content);
    }
}
